<script  setup>
import api from '../api/product_api.js'
import brand_api from '../api/brand_api.js'
import category_api from '../api/category_api.js'
import sizeApi from '../api/size_api.js';
import productSizeApi from '../api/product_size_api.js';
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import lodash from 'lodash'
import router from "@/router/index.js";


// 表格数据
const tableData = ref([]);
// 总条数（分页用）
const total = ref(0);
// 弹窗显示状态
const editWinVisible = ref(false);
/*const selectBrandWinVisible = ref(false);*/

const sizeList = ref([]);

// 搜索和分页参数
const searchObj = ref({
  current: 1,
  limit: 10,
  product_name: '',
  purchase_price: '',
  selling_price: '',
  material: '',
  category_id: '',
  brand_id: '',
  /*brand: '',*/
  /*brand.brand_name: '',*/
});

// 新增/编辑的数据对象
const obj = ref({});
const brands = ref([]);
const categories = ref([]);
/*const reseve = ref({});*/
/*const currentRow = ref(null);*/


// 加载数据列表
const search = async () => {
  const params = { ...searchObj.value };
  // 处理空搜索条件，避免%%查询
  if (params.product_name === '') delete params.product_name;
  if (params.purchase_price === '') delete params.purchase_price;
  if (params.selling_price === '') delete params.selling_price;
  if (params.material === '') delete params.material;
  if (params.category_id === '') delete params.category_id;
  if (params.brand_id === '') delete params.brand_id;
  const res = await api.page(params);
  tableData.value = res.data;
  total.value = res.count;
};

// 页面加载时初始化数据
onMounted(async () => {
  await search();
});

const handleUploadSuccess = (response, file) => {
  obj.value.photo = response.data;
}

const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};


// 分页-每页条数变化
const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  search();
};

// 分页-当前页变化
const handleCurrentChange = (val) => {
  searchObj.value.current = val;
  search();
};

const handlerSearch = async () => {
  searchObj.value.current = 1;
  search();
};

const handlerAdd = async () => {
  obj.value = { product_name: '', purchase_price: '', selling_price: '', material: '', category_id: '', brand_id: '' };
  // 加载品牌数据
  brands.value = await brand_api.all();
  // 加载分类数据
  categories.value = await category_api.all();
  editWinVisible.value = true;
};

const editCommit = async () => {
  if (!obj.value.product_name) {
    ElMessageBox.alert('产品名不能为空', '提示', { type: 'warning' });
    return;
  }

  if (obj.value.id) {
    await api.edit(obj.value);
  } else {
    await api.add(obj.value);
    searchObj.value.current = 1;
  }


  search();
  editWinVisible.value = false;
};

/*const confirmBrandSelect = async () => {
  if (currentRow.value) {
    currentRow.value.brand_id = reseve.value.brand_id;
    await api.edit(currentRow.value);
    search();
  }
  selectBrandWinVisible.value = false;
};*/

const handleEdit = async (index, row) => {
  obj.value = lodash.clone(row);
  // 加载品牌数据
  brands.value = await brand_api.all();
  // 加载分类数据
  categories.value = await category_api.all();
  editWinVisible.value = true;
};

/*const handleSelect = async (index, row) => {
  currentRow.value = row;
  brands.value = await brand_api.all();
  selectBrandWinVisible.value = true;
}*/
const handleStock = async (index, row) => {
  router.push({
    name: 'product_size',  // 建议使用命名路由
    query: { product_id: row.id }  // 或者使用 params: { id: row.id } 配合动态路由
  });
};

const handleDelete = async (index, row) => {
  ElMessageBox.confirm(
      '真的要删除吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await api.del(row.id);
        searchObj.value.current = 1;
        search();
      })
      .catch(() => {
      });
};
</script>

<template>
  <!-- 搜索表单 -->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-bottom: 10px;">
    <el-form-item label="产品名">
      <el-input v-model="searchObj.product_name" placeholder="请输入产品名" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handlerAdd">新增</el-button>
    </el-form-item>
  </el-form>

  <!-- 数据表格 -->
  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="产品" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span style="margin-left: 10px">{{ scope.row.product_name }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="图片" width="80">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <img :src="scope.row.photo" style="width: 100px; height: 80px;">
        </div>
      </template>
    </el-table-column>

    <el-table-column label="进价" width="180">
      <template #default="scope">
        {{ scope.row.purchase_price }}
      </template>
    </el-table-column>

    <el-table-column label="售价" width="180">
      <template #default="scope">
        {{ scope.row.selling_price }}
      </template>
    </el-table-column>

    <el-table-column label="材质" width="180">
      <template #default="scope">
        {{ scope.row.material }}
      </template>
    </el-table-column>

    <el-table-column label="分类" width="180">
      <template #default="scope">
        {{scope.row.category?.category_name || '无分类'  }}
      </template>
    </el-table-column>

    <el-table-column label="品牌" width="180">
      <template #default="scope">
        {{scope.row.brand?.brand_name || '无品牌' }}
      </template>
    </el-table-column>

    <el-table-column label="处理按钮">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
<!--        <el-button size="small" @click="handleSelect(scope.$index, scope.row)">
          品牌
        </el-button>-->
        <el-button size="small"  type="primary" @click="handleStock(scope.$index, scope.row)">
          详情
        </el-button>


      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

<!--  <el-dialog v-model="selectBrandWinVisible" title="选择品牌" width="500">
    <el-form :model="reseve">
      <el-form-item label="品牌" :label-width="100">
        <el-select v-model="reseve.brand_id" placeholder="请选择" style="width: 240px">
          <el-option v-for="item in brands" :key="item.id" :label="item.brand_name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="confirmBrandSelect">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>-->

  <!-- 新增/编辑弹窗 -->
  <el-dialog v-model="editWinVisible" :title="obj.id ? '编辑产品' : '新增产品'" width="500">
    <el-form :model="obj">
      <!-- 编辑时显示id（禁用），新增时隐藏 -->
      <el-form-item label="id" :label-width="100" v-if="obj.id">
        <el-input v-model="obj.id" autocomplete="off" disabled />
      </el-form-item>
      <el-form-item label="产品名" :label-width="100">
        <el-input v-model="obj.product_name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="图片" :label-width="100">
        <el-upload class="avatar-uploader" action="/api/upload/file" :show-file-list="false"
                   :on-success="handleUploadSuccess">
          <img v-if="obj.photo" :src="obj.photo" style="width:100px" />
          <img v-else src='@/assets/upload.png' style="width:100px" />
        </el-upload>
      </el-form-item>
      <el-form-item label="进价" :label-width="100">
        <el-input v-model="obj.purchase_price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="售价" :label-width="100">
        <el-input v-model="obj.selling_price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="材质" :label-width="100">
        <el-input v-model="obj.material" autocomplete="off" />
      </el-form-item>
      <el-form-item label="分类" :label-width="100">
        <el-select v-model="obj.category_id" placeholder="请选择分类" style="width: 240px">
          <el-option v-for="item in categories" :key="item.id" :label="item.category_name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- 品牌选择下拉框 -->
      <el-form-item label="品牌" :label-width="100">
        <el-select v-model="obj.brand_id" placeholder="请选择品牌" style="width: 240px">
          <el-option v-for="item in brands" :key="item.id" :label="item.brand_name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>
